<?php
namespace app\admin\controller;

use think\Controller;

use app\admin\service\UserService;

class Auth extends Controller
{

    private $service;

    private $requestData;

    public function __construct()
    {
        parent::__construct();

        if( $_POST ){
            $input = $_POST;
        }else{
            $input = json_decode(file_get_contents('php://input'),true);
        }
        $this->requestData = $input;

        $this->service = new UserService;

    }

    public function login()
    {
        $data = $this->requestData;
        $userInfo  = $this->checkUser( $data );
        $userInfo['token'] = $this->setToken($userInfo['id']);
        jsonMsg(200,'登录成功',$userInfo);
    }

    private function checkUser( $data=[] )
    {
        $info = $this->service->detail([
            'username' => $data['username'],
        ],'*');
        if( empty($info) ){
            jsonMsg(0,'账号不存在');
        }
        if( $info['password'] != $data['password'] ){
            jsonMsg(0,'密码不正确');
        }
        return $info;
    }

    private function setToken( $userId )
    {
        $token = md5($userId.sha1(substr(time(),3,7)));
        $res = $this->service->edit($userId,[
            'token' => $token
        ]);
        if( $res ){
            cache($token, $userId, 3600 * 2);
        }else{
            jsonMsg(0,'系统错误');
        }
        return $token;
    }

}
